#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>


int client_creat(int* sockfd){
    *sockfd = socket(AF_INET,SOCK_STREAM,0);//ipv4,tcp
    if(*sockfd == -1){
        perror("sock err");
        return -1;
    }
    //服务器地址:IP 端口号
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    // server_addr.sin_port =htons(atoi(argv[2]));
    server_addr.sin_port =htons(8080);

    // server_addr.sin_addr.s_addr=inet_addr(argv[1]);
    server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");

    printf("IP=%s\n",inet_ntoa(server_addr.sin_addr));
    socklen_t addrlen= sizeof(server_addr);
    

    //连接
    if(connect(*sockfd,(struct sockaddr*)&server_addr,addrlen) < 0){
        perror("coonet err");
        close(*sockfd);
        return -1;
    }
    printf("connet  success\n");

    return 0;
}

int main(int argc, char const *argv[])
{
    // if(argc < 2){
    //     printf("usage err\n");
    //     return -1;
    // }

    int n=5;
    int sockfd=-1;
    char buf[64] = "abcdefg";
	for(int i = 0; i < n; i++)
    {
        pid_t pid = fork();
        if(pid < 0){
            perror("fork err");
            return -1;
        }else if(pid > 0)
        {   
            if(client_creat(&sockfd) < 0){
                return -1;
            }
            if (send(sockfd, buf, 64, 0) == -1)
            { // send 不一定会一次全部发送完，分多次发送完
                perror("send err");
                // break;
            }
            wait(NULL);
            printf("in parent (PID:%d),child:%d\n",getpid(),pid);
            close(sockfd);

            exit(0);
        }
    }
    if(client_creat(&sockfd) < 0){
        return -1;
    }
    if (send(sockfd, buf, 64, 0) == -1)
    { // send 不一定会一次全部发送完，分多次发送完
        perror("send err");
        // break;
    }

    printf("in child (PID:%d), parent:%d\n",getpid(),getppid());
    
    close(sockfd);

    return 0;
}
